﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

using log4net;
using AutoFacUtils;
using CashFlow.Db.Entity;
using CashFlow.Web.Service;
using CashFlow.Db.Repository;
using CashFlow.Web.Models;
using CashFlow.Web.MyActionResult;
using CashFlow.Web.Validator;
using CashFlow.Web.Common;
using CashFlow.Web.Filters;

namespace CashFlow.Web.Controllers
{
    public class UserController : Controller
    {
        private static ILog _logger = LogManager.GetLogger(typeof(UserController));
        private IUserService GetUserService() { return AutoFacHelper.Get<IUserService>(); }
        private IUserInfoRepository GetUserInfoRepository() { return AutoFacHelper.Get<IUserInfoRepository>(); }
        private IShopService GetShopService() { return AutoFacHelper.Get<IShopService>(); }
        private IOrderService GetOrderService() { return AutoFacHelper.Get<IOrderService>(); }

        // GET: User
        public ActionResult Index()
        {
            var userService = GetUserService();
            var ui = userService.GetLoginUser() as UserInfoEntity;
            var repos = GetUserInfoRepository();
            var ui2 = repos.QueryByReferenceInvitationCode(ui.ReferenceInvitationCode);
            var shopService = GetShopService();
            var shopInfo = shopService.QueryShopInfoByUserId(ui.Id);
            var ui3 = userService.QuerySingleById(shopInfo.ShopManagerUserId);
            var orderService = GetOrderService();
            var date = MyCommonTool.GetOrderDate();
            var count = orderService.QueryShopAllChildUsersOrderCount(ui.Id, date, 1, null);
            ViewBag.UserInfo = ui;
            ViewBag.ReferenceUserInfo = ui2;
            ViewBag.ShopInfo = shopInfo;
            ViewBag.ShopManagerInfo = ui3;
            ViewBag.ShopLevelName = ShopManagerLevelTool.GetShopManagerLevelName(count);

            return View();
        }

        public ActionResult UpdatePwd()
        {
            return View();
        }

        [HttpPost]
        [ValidatorFilter(typeof(UpdatePwdModelValidator))]
        public ActionResult UpdatePwd(UpdatePwdModel model)
        {
            string msg = "";
            var service = GetUserService();
            bool bSuccess = service.UpdatePwd(model.OldPwd, model.NewPwd);
            if (bSuccess)
            {
                service.Logout();
            }
            else
            {
                msg = "原密码不正确！";
            }

            return MyCommonTool.CreateOperationResult(bSuccess, msg, null);
        }

        public ActionResult MyCustomers()
        {
            var service = GetUserService();
            var ui = service.GetLoginUser();
            var ls = service.QueryShopFstGenChildUsersByUserId(ui.Id, 1);
            ViewBag.MyCustomers = ls;

            return View();
        }
    }
}